import EchartsComponent, { MyChartOption } from '@/components/EchartsComponent';
import { getEmptyOptions } from '@/dictionary';
import { statisticElectricityControllerGenerateDayReportGraph } from '@/services/ess/statisticElectricity';
import { useIntl } from '@umijs/max';
import { Spin } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import { getBlueColor, getGreenColor } from '../helper';
import ChartForm from './ChartForm';

type IProps = {
  dateType?: string;
};
const DayChart: React.FC<IProps> = () => {
  const intl = useIntl();
  const [options, setOptions] = useState<MyChartOption>({});
  const chartRef = useRef(null);
  const [chartLoading, setChartLoading] = useState(false);
  /**
   * 获得Y轴数据
   * @param options
   */
  const getYaxis = (options) => {
    return options.map((item) => {
      return item.yaxis;
    });
  };
  const addOneHour = (timeString: string) => {
    const [hour, minute, second] = timeString.split(':').map((item) => parseInt(item));
    const date = new Date();
    date.setHours(hour);
    date.setMinutes(minute);
    date.setSeconds(second);
    date.setHours(date.getHours() + 1);
    return `${date.getHours().toString().padStart(2, '0')}:${date
      .getMinutes()
      .toString()
      .padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
  };
  const submitForm = (value) => {
    if (options) {
      setChartLoading(true);
    }
    console.log('value', value);
    const params = {
      areaFlag: value.areaFlag,
      date: dayjs(value.date).format('YYYY-MM-DD'),
      codes: value?.code || undefined,
    };
    statisticElectricityControllerGenerateDayReportGraph(params)
      .then((res) => {
        if (res.success && res.data) {
          chartRef?.current?.instance().clear();
          setOptions({
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow',
              },
            },
            legend: {
              type: 'scroll',
              width: '80%',
              top: 20,
              right: 0,
              icon: 'rect',
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true,
            },
            xAxis: [
              {
                type: 'category',
                data: res?.data?.xaxis?.map((value) => {
                  return `${value}-${addOneHour(value)}`;
                }),
                axisTick: {
                  alignWithLabel: true,
                },
                axisLabel: {
                  formatter: function (params: string) {
                    return `${Number(params.slice(0, 2))}`;
                  },
                },
              },
            ],
            yAxis: [
              {
                name: intl.formatMessage({ id: 'statistics.common.unitkWh' }),
                type: 'value',
                axisLine: {
                  show: true,
                },
              },
            ],
            series: res?.data?.yaxis
              ?.sort((a, b) => (a.deviceName ?? '').localeCompare(b.deviceName ?? ''))
              .map((item, index) => {
                const colorIndex = Math.floor(index / 2);
                return {
                  type: 'bar',
                  name:
                    value.staticDimension === 'station'
                      ? item.title
                      : item.deviceName + '-' + item.title,
                  stack: item.deviceName + '' + colorIndex,
                  itemStyle: {
                    color: item.title?.includes(
                      intl.formatMessage({ id: 'statistics.work.discharge' }),
                    )
                      ? getBlueColor(colorIndex)
                      : getGreenColor(colorIndex),
                  },
                  barWidth: '20%',
                  data: getYaxis(item.points),
                };
              }),
          });
          setChartLoading(false);
        } else {
          if (
            chartRef?.current?.instance() &&
            chartRef?.current?.instance().getOption()?.series.length !== 0
          ) {
            chartRef?.current?.instance().clear();
          }
          setOptions(getEmptyOptions());
          setChartLoading(false);
        }
      })
      .catch(() => {
        setChartLoading(false);
      });
  };
  useEffect(() => {
    setChartLoading(true);
  }, []);
  return (
    <div style={{ marginTop: '10px', marginLeft: '10px' }}>
      <ChartForm dateType={'date'} submitForm={submitForm} />
      <Spin spinning={chartLoading}>
        <EchartsComponent
          option={options}
          width={'auto'}
          height={550}
          ref={chartRef}
        ></EchartsComponent>
      </Spin>
    </div>
  );
};

export default DayChart;
